package myjava.b_array;

/**
 * @Auther: cty
 * @Date: 2019/10/29
 * @Description: 测试数组拷贝System.arraycopy()
 * @version: 1.0
 */
public class A_ArrayCopy {
    public static void main(String[] args) {
        testBasicCopy();
        System.out.println();
        testBasicCopy2();
        System.out.println();

        String[] ss = {"00","11","22","33","44","55"};
        //System.out.println(removeElement(ss,1));
        extendRange(ss,10);

    }

    /**
     * 数组的拷贝
     * 0-null
     * 1-null
     * 2-null
     * 3-null
     * 4-null
     * 5-null
     * 6-cc
     * 7-dd
     * 8-ee
     * 9-null
     */
    public static void testBasicCopy(){
        String[] s1 = {"aa","bb","cc","dd","ee"};
        String[] s2 = new String[10];
        System.arraycopy(s1,2,s2,6,3);

        for(int i=0;i<s2.length;i++){
            System.out.println(i+"-"+s2[i]);
        }
    }

    /**
     * 从数组中删除某个元素，本质是数组的拷贝
     * 0-aa
     * 1-bb
     * 2-dd
     * 3-ee
     * 4-null
     */
    public static void testBasicCopy2(){
        String[] s1 = {"aa","bb","cc","dd","ee"};
        //String[] s2 = new String[10];
        System.arraycopy(s1,4-1,s1,3-1,2);
        s1[s1.length-1] = null;

        for(int i=0;i<s1.length;i++){
            System.out.println(i+"-"+s1[i]);
        }
    }

    //删除数组中指定索引位置(1-n)的元素，并将原数组返回
    public static String[] removeElement(String[] s,int index){
        System.arraycopy(s,index+1,s,index,s.length-index-1);
        s[s.length-1] = null;

        for(int i=0;i<s.length;i++){
            System.out.println(i+"-"+s[i]);
        }
        return s;
    }

    //数组的扩容（本质上是先定义一个更大的数组，然后将原数组的内容原封不动的拷贝到新数组中）
    public static String[] extendRange(String[] s1,int n) {
        String[] s2 = new String[s1.length+n];
        System.arraycopy(s1,0,s2,0,s1.length);

        for(String temp:s2){
            System.out.println(temp);
        }
        return s2;
    }
}
